package ioc

import (
	accountv1 "booksmart/book/api/proto/gen/account/v1"
	_ "booksmart/book/pkg/grpcx/balance"
	"booksmart/book/pkg/grpcx/registry/nacos"
	"github.com/spf13/viper"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/resolver"
)

func InitAccountClientByNacos(builder *nacos.NacosBuilder) accountv1.AccountServiceClient {
	type Config struct {
		Addr      string
		Secure    bool
		Threshold int32
		Name      string
	}
	var cfg Config
	err1 := viper.UnmarshalKey("grpc.client.account", &cfg)
	if err1 != nil {
		panic(err1)
	}
	var opts []grpc.DialOption
	if cfg.Secure {
		//启动HTTPS
	} else {
		opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))
	}
	builder.ServiceName = cfg.Name

	resolver.Register(builder)
	var config = `{"loadBalancingConfig": [{"custom_wrr":{}}]}`
	opts = append(opts, grpc.WithDefaultServiceConfig(config))
	cc, err := grpc.Dial("nacos:///"+builder.ServiceName, opts...)
	if err != nil {
		panic(err)
	}
	remote := accountv1.NewAccountServiceClient(cc)
	return remote
}

//func InitAccountClient(etcdClient *etcdv3.Client) accountv1.AccountServiceClient {
//	type Config struct {
//		Target string `json:"target"`
//		Secure bool   `json:"secure"`
//	}
//	var cfg Config
//	err := viper.UnmarshalKey("grpc.client.account", &cfg)
//	if err != nil {
//		panic(err)
//	}
//	rs, err := resolver.NewBuilder(etcdClient)
//	if err != nil {
//		panic(err)
//	}
//	opts := []grpc.DialOption{grpc.WithResolvers(rs)}
//	if !cfg.Secure {
//		opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))
//	}
//	cc, err := grpc.Dial(cfg.Target, opts...)
//	if err != nil {
//		panic(err)
//	}
//	return accountv1.NewAccountServiceClient(cc)
//}
